//
//  JPComposeTextView.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 2016/10/5.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

class JPComposeTextView: UITextView {

    lazy var placeHolderLabel: UILabel = {
        let label = UILabel(textColor: UIColor.lightGray, fontSize: 12)
        label.numberOfLines = 0
        label.text = "别低头,绿帽会掉~"
        label.sizeToFit()
        
        return label
    }()

    override var text: String! {
        didSet {
            placeHolderLabel.isHidden = hasText
        }
    }
    
    override var font: UIFont? {
        didSet {
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        addSubview(placeHolderLabel)
        
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
    
    }
    
    @objc private func textChanged() {
        placeHolderLabel.isHidden = true
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
